/*
 * @Author: Wangtao
 * @Date: 2022-07-26 14:26:31
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-08-23 17:33:16
 */
import { normalizeClass, VNode, mergeProps as _mergeProps } from "vue"
import { preCls, Props } from "./interface"

export const patchClass = (el: HTMLElement, clazz: any, oldClazz: any) => {
  clazz = clazz.split(' '), oldClazz = oldClazz.split(' ')
  const delCls = oldClazz.filter((e: any) => !clazz.includes(e)), addCls = clazz
  delCls.forEach((e: any) => e && el.classList.remove(e))
  addCls.forEach((e: any) => e && el.classList.add(e))
}

export const getLoading = (binding: any) => typeof binding.value === 'object' ? binding.value.loading : binding.value

export const getAnimated = (binding: any): boolean => binding.modifiers.animated

export const getClass = (binding: any) => {
  const loading = getLoading(binding)
  if (!loading) return ''
  const animated = getAnimated(binding)
  return normalizeClass([preCls, { [`${preCls}-animated`]: animated }, binding.value.loadingClass])
}

export const allClass = (binding: any) => {
  return normalizeClass([preCls, `${preCls}-animated`, binding.value.loadingClass])
}

export const fliterClass = (cls: string) => {
  return cls.split(' ').filter(cls => cls.includes(preCls)).join(' ')
}

export function mergeProps(vnode: any, binding: any) {
  if (getLoading(binding)) {
    if (vnode.props) {
      const props = _mergeProps(vnode.props, {
        class: getClass(binding),
      })
      props.class = [...new Set((props.class as string).split(' '))].join(' ')
      Object.assign(vnode.props, props)
    } else {
      const clazz = normalizeClass([vnode.el.className, getClass(binding)])
      vnode.el.className = clazz
    }
  }
}